package br.com.vendaweb.integracao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;

public abstract class DAOGenerico<T>{
	private HibernateTemplate hibernateTemplate;
	@Autowired
	private SessionFactory sessionFactory;
	
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		if (this.hibernateTemplate == null || sessionFactory != this.hibernateTemplate.getSessionFactory()) {
			this.hibernateTemplate = createHibernateTemplate(sessionFactory);
		}
	}
	
	protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) {
		return new HibernateTemplate(sessionFactory);
	}
	public final SessionFactory getSessionFactory() {
		return (this.hibernateTemplate != null ? this.hibernateTemplate.getSessionFactory() : null);
	}
	public final HibernateTemplate getHibernateTemplate() {
	  return this.createHibernateTemplate(sessionFactory);
	}

	public List<T> listar() {		
		Class<T> tipo = getTipoDaEntidade();		
		return getHibernateTemplate().loadAll(null);
	}

	protected Class<T> getTipoDaEntidade() {
		Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; 
		return clazz;
	}

	public void salvar(T entidade) {
		getHibernateTemplate().saveOrUpdate(entidade);
	}

	public T obter(Serializable id) {
		// TODO Auto-generated method stub
		return null;
	}

	public void inserir(T entidade) {
		getHibernateTemplate().save(entidade);		
	}
}
